package com.linshengjian.power.service.imp;

import com.linshengjian.core.BaseDao;
import com.linshengjian.core.BaseModel;
import com.linshengjian.core.BaseService;
import com.linshengjian.core.BusinessException;
import com.linshengjian.power.dao.RoleDao;
import com.linshengjian.power.entity.PermissionEntity;
import com.linshengjian.power.entity.ResourcesEntity;
import com.linshengjian.power.entity.RoleEntity;
import com.linshengjian.power.model.Permission;
import com.linshengjian.power.model.Role;
import com.linshengjian.power.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService extends BaseService<RoleEntity, Role, Integer> implements IRoleService {

    private final static String roleNotFind = "角色对象不存在";
    private final static String permissionNotFind = "权限对象不存在";

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionService permissionService;


    @Override
    protected BaseDao<RoleEntity, Integer> dao() {
        return roleDao;
    }

    @Override
    protected RoleEntity model2Entity(Role model) {
        RoleEntity entity = new RoleEntity();
        entity.setId(model.getId());
        entity.setName(model.getName())
                .setDescription(model.getDescription())
                .setStatus(model.getStatus());
        return entity;
    }

    @Override
    protected Role entity2model(RoleEntity entity) {
        Role model = new Role();
        model.setId(entity.getId());
        model.setName(entity.getName())
                .setDescription(entity.getDescription())
                .setStatus(entity.getStatus());
        return model;
    }

    @Override
    public void addPermission(Integer rid, Integer pid) throws BusinessException {
        RoleEntity role = dao().findOne(rid);
        if (role == null)
            throw new BusinessException(roleNotFind);

        PermissionEntity permission = permissionService.dao().findOne(pid);
        if (permission == null)
            throw new BusinessException(permissionNotFind);

        role.getPermissions().add(permission);

        dao().save(role);
    }

    @Override
    public void delPermission(Integer rid, Integer pid) throws BusinessException {
        RoleEntity role = dao().findOne(pid);
        if (role == null)
            throw new BusinessException(roleNotFind);
        for (PermissionEntity per: role.getPermissions()) {
            if (per.getId().equals(rid)) {
                role.getPermissions().remove(per);
                break;
            }
        }
        dao().save(role);
    }

    @Override
    public List<Permission> permission(Integer id) throws BusinessException {
        RoleEntity role = dao().findOne(id);
        if (role == null)
            throw new BusinessException(roleNotFind);

        return permissionService.entity2Model(role.getPermissions());
    }
}
